﻿
from strategy_platform.api import (sub_realmd,unsub_realmd,register_realmd_cb)
from strategy_platform.api import (sub_order, submit_order, cancel_order, register_order_cb)
from strategy_platform.api import (submit_order,query_order,cancel_order, query_position,query_commodity_info,query_credit_fund_info)
from strategy_platform.api import (add_argument)
from strategy_platform.api import (second_timer, minute_timer, at_day_timer, get_trade_days)
from datetime import datetime, timedelta, date
import time, math, pandas 
import threading  
import util

lock_oo = threading.Lock()
	
#add_argument("target_file", str, 0, 'D:\\prod\\s001\\targetpos\\test_stock200.csv') #弹出设置参数的窗口, argument_dict 在这步以后被设置
#add_argument("prev_date",   int, 1, 0)
#add_argument("capital_ps",  float, 1, 2e3) #2000 per symbol
#add_argument("capital_total",  float, 1, 500e4)
#start_time = "09:30:00"
#end_time   = "09:40:00"

def on_init(argument_dict):
	global g
	g = {}
	g['acct_type']   = "C" #"SHHTSC" 
	g['acct']        = "8009180103" #"2497312"
	
	for k, v in argument_dict.items():
		g[k] = v
	log.info(g)
	register_order_cb(on_order_update, None)  
	sub_order(g['acct_type'], g['acct'], False) #只关注策略发出的订单  
	
	# 全局变量
	g['orders'] = {}
		
	d = util.gen_targetpos_sk001(250e4) #code, w1000, price, targetpos
	d['qty'] = d['targetpos']
	log.info('There are %d stocks in the targetpos, %d positive position, %d have non-zero to-do qty'%(len(d), (d.targetpos>0).sum(), (d.qty!=0).sum()))
	log.info(d.head(2))
	g['target_orders'] = d[d.qty!=0]
	log.info('will place %d opening orders'%(len(g['target_orders'])))
	
	at_day_timer("09:24", send_orders_)  
	at_day_timer("09:27", cancel_orders_)
	
def on_order_update(order_obj, cb_arg):   

	# status = 0: 新单
	# status = 1: 部成
	# status = 2: 全成
	# status = 3: 部撤
	# status = 4: 全撤
	# 拒单
	log.info('in orer_response')
	if order_obj.symbol == '000050.SZ':
		log.info("order update: [symbol:{}, orderNo:{}, price:{}, qty:{}, stauts:{}, filledQty:{}, avgPrice:{}, cancelQty:{}, orderTime:{}, orderDate:{}]".format(order_obj.symbol, \
		order_obj.orderNo, order_obj.price, order_obj.qty, order_obj.status, order_obj.filledQty, order_obj.avgPrice, order_obj.cancelQty, order_obj.orderTime, order_obj.orderDate))  
	
	lock_oo.acquire()
	g['orders'][oid] = order_obj
	lock_oo.release()


def send_orders_(*args, **kwargs):
	for row in g['target_orders'].head(5).itertuples():
		send_order_(row.code, row.qty, row.price)
		

def cancel_orders_(*args, **kwargs):
	ncancel = 0
	for oid, order_obj in g['orders'].items():
		qty_left = order_obj.qty - order_obj.filledQty
		if qty_left != 0:
			cancel_order(g['acct_type'], g['acct'], oid)
			ncancel = ncancel+1
	log.info('%d orders cancelled'%ncancel)

def on_fini():
	unsub_order(g['acct_type'], g['acct'])   
	unregister_order_cb()  
 


#second_timer(5, send_orders_)


